package com.sxt.sys.controller;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sxt.sys.domain.User;
import com.sxt.sys.service.LogInfoService;
import com.sxt.sys.service.UserService;
import com.sxt.sys.utils.WebUtils;
import com.sxt.sys.vo.LogInfoVo;
import com.sxt.sys.vo.UserVo;

@Controller
@RequestMapping("Login")
public class LoginController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private LogInfoService logInfoService;
	
	//跳转到登录界面
	@RequestMapping("toLogin")
	public String toLogin(){
		return "main/login";
	}
	
	
	//登录
	@RequestMapping("login")
	public String login(UserVo userVo,Model model){
		User user = userService.login(userVo);
		if(null!=user){
			WebUtils.getCurrentSession().setAttribute("user", user);
			
			//记录登陆日志
			String ip=WebUtils.getCurrentRequest().getRemoteAddr().toString();  
			LogInfoVo logInfoVo = new LogInfoVo();
			logInfoVo.setLoginip(ip);
			logInfoVo.setLoginname(user.getLoginname()+"-"+user.getRealname());
			logInfoVo.setLogintime(new Date());
			logInfoService.addLogInfo(logInfoVo);
					return "main/index";
		}else{
			model.addAttribute("error", "用户名或密码有误");
			
			return "main/login";
		}
		
	}
	
	//退出，至登录界面
	@RequestMapping("loginOut")
	public String loginOut(){
		HttpSession session = WebUtils.getCurrentSession();
		session.invalidate();
		return "main/login";
		
	}
}
